//
//  OAMyApprovalViewController.m
//  ERP
//
//  Created by goldeney on 15/1/19.
//  Copyright (c) 2015年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "OAMyApprovalViewController.h"
#import "GETableViewButtonCell.h"
#import "OAMyBriefcaseClassCell.h"
#import "OAReadApplyHtmlViewController.h"

#import "MJRefresh.h"
#import "OAApplyApprovalViewCell.h"
#import "UITableView+Custom.h"
#import "GEObjectButton.h"

#import "NSKeyedArchiverUserLogin.h"
#import "NSDictionary+DataFormat.h"

#import "ServiceConnect.h"
#import "DownLoadHandle.h"
#import "PreviewFileHelper.h"
#import "GEAccessoryPreview.h"

#import "UITableView+Custom.h"
#import "OAApprovalDetailViewController.h"

@interface OAMyApprovalViewController ()<SKSTableViewDelegate,GETableViewButtonCellDelagate>

@property (strong, nonatomic) NSMutableArray *resultData;
@property (strong, nonatomic) NSMutableArray *searchData;

@property (assign, nonatomic) NSInteger segmentActionState;

@property (strong, nonatomic) UIView *searchMainView;
@property (strong, nonatomic) UITableView *searchTableView;

@end

@implementation OAMyApprovalViewController
@synthesize tableView = _tableView;
//@synthesize searchView = _searchView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle: @"我的审批"];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.resultData = [NSMutableArray array];
    
    self.tableView.SKSTableViewDelegate = self;
    self.tableView.shouldExpandOnlyOneCell = YES;
    self.tableView.tableFooterView= [[UIView alloc] init];
    
    [self.segmentedView setTintColor:ThemeColorBlue];
    [self.segmentedView addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    [self setupRefresh];//启动下拉
}

- (void)setupRefresh
{
    //添加下拉加载数据
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    [self.tableView headerBeginRefreshing];
    [self.tableView footerEndRefreshing];
}

- (void)stopRefresh
{
    //移除下拉加载数据
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
}

//具体委托方法实例
-(void)segmentAction:(UISegmentedControl *)Seg
{
    NSInteger index = Seg.selectedSegmentIndex;
    self.segmentActionState = index;
    
    [self.resultData removeAllObjects];
    [self.tableView refreshData];
    [self.tableView headerBeginRefreshing];
}

#pragma mark 网络获取数据

- (void)getNetWorkDataIsReresh:(BOOL)isReresh state:(NSNumber*)state end:(NSNumber*)end
{
    //获取用户登录信息
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    
    //审批状态:0进行中，1已通过，2未通过,3已执行
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    [model setValue:userInfo.Id forKey:@"userid"];
    [model setValue:[NSNumber numberWithInteger:self.segmentActionState] forKey:@"apptype"];
    [model setValue:state forKey:@"between"];
    [model setValue:end forKey:@"and"];
    [model setValue:@"" forKey:@"searchVal"];
    
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"OA_MyApproval" dataArray:model];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if(isReresh) [self.tableView headerEndRefreshing];
        else [self.tableView footerEndRefreshing];
        //添加数据，刷新页面
        if(result.resultArray && result.resultArray.count>0){
            if(isReresh) [self.resultData removeAllObjects];
            [self.resultData addObjectsFromArray:result.resultArray];
            [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
            [self.tableView refreshData];
        } else if(isReresh) {
            [self.tableView setTableViewNotDataDrawText:@"暂无审批" isShow:YES];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        if(isReresh) [self errorInfoViewText:@"哦，出错了"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        if(isReresh) [self errorInfoViewText:@"无法连接网络"];
    }];
}

- (void)errorInfoViewText:(NSString*)label
{
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
    
    if (self.tableView.visibleCells.count <= 0) {
        [self.tableView setTableViewNotDataDrawText:label isShow:YES];
    } else {
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        [self showErrorHUDText:label];
    }
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:1];
    NSNumber *endNumber = [NSNumber numberWithInteger:10];
    [self getNetWorkDataIsReresh:YES state:stateNumber end:endNumber];
}

- (void)footerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:self.resultData.count +1];
    NSNumber *endNumber = [NSNumber numberWithInteger:self.resultData.count + 10];
    [self getNetWorkDataIsReresh:NO state:stateNumber end:endNumber];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.resultData.count;
}

- (NSInteger)tableView:(SKSTableView *)tableView numberOfSubRowsAtIndexPath:(NSIndexPath *)indexPath
{
    return 1;
}

- (UITableViewCell *)tableView:(SKSTableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"OAApplyApprovalViewCell";
    OAApplyApprovalViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell){
        cell = [[OAApplyApprovalViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        [cell setExpandable:YES];
    }
    
    cell.openUpButton.object = indexPath;
    [cell.openUpButton addTarget:self action:@selector(openSelectRowSelector:) forControlEvents:UIControlEventTouchUpInside];
    
    //审批状态:0进行中，1已通过，2未通过，3已执行
    NSDictionary *model = [self.resultData objectAtIndex:indexPath.row];
    NSInteger mState = [[model objectFormatStringForKey:@"approvalstate"] integerValue];
    if (mState == 0) cell.stateLable.text = @"进行中";
    else if (mState == 1) cell.stateLable.text = @"已通过";
    else if (mState == 2) cell.stateLable.text = @"未通过";
    else if (mState == 3) cell.stateLable.text = @"已执行";
    
    cell.timeLable.text = [model objectFormatStringForKey:@"creationTime"];
    cell.peopleLable.text = [model objectFormatStringForKey:@"sponsorid"];
    
    //是否阅读标记
    if(self.segmentActionState != 0){
        cell.readMark.hidden = YES;
        cell.titleLable.text = [model objectFormatStringForKey:@"templatename"];
    } else {
        NSString *title = [model objectFormatStringForKey:@"templatename"];
        cell.readMark.hidden = NO;
        cell.titleLable.text = [NSString stringWithFormat:@"         %@",title];
    }
    
    return cell;
}

- (void)openSelectRowSelector:(GEObjectButton*)button
{
    NSIndexPath *indexPath = button.object;
    [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *mDictionary = [self.resultData objectAtIndex:indexPath.row];
    NSArray *valueData = @[mDictionary,@2];
    OAApprovalDetailViewController *view = [[OAApprovalDetailViewController alloc] initWithValue:valueData];
    view.backResultDelagate = self;
    [self.navigationController pushViewController:view animated:YES];
}

- (UITableViewCell *)tableView:(SKSTableView *)tableView cellForSubRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"GETableViewButtonCell";
    GETableViewButtonCell *cell = [[GETableViewButtonCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    
    [cell drawRectButtonName:@"预览" imageName:@"oa_icon_search_empty.png" tagIndex:1];
    
    NSDictionary *model = [self.resultData objectAtIndex:indexPath.row];
    NSArray *fileArray = [model objectFormatForKey:@"fjlist"];
    if ([fileArray isKindOfClass:[NSArray class]] && fileArray.count > 0)
        [cell drawRectButtonName:@"附件" imageName:@"oa_read_info_btn.png" tagIndex:2];
    
    cell.delagate = self;
    [cell setIndexPath:indexPath];
    return cell;
}

- (CGFloat)tableView:(SKSTableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

- (CGFloat)tableView:(SKSTableView *)tableView heightForSubRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

#pragma mark - GETableViewButtonCellDelagate

- (void) cellButtonEvent:(NSIndexPath*)indexPath tagIndex:(int)tagIndex
{
    NSDictionary *mDictionary = [self.resultData objectAtIndex:indexPath.row];
    if (tagIndex == 1) {//预览
        NSString *Appurl = [mDictionary objectFormatStringForKey:@"appurl"];
        OAReadApplyHtmlViewController *view = [[OAReadApplyHtmlViewController alloc] initWithNibUrl:Appurl];
        [self.navigationController pushViewController:view animated:YES];
        
    } else if (tagIndex == 2) {//附件
        NSArray *fileArray = [mDictionary objectFormatForKey:@"fjlist"];
        GEAccessoryPreview *showAccessory = [[GEAccessoryPreview alloc] init];
        [showAccessory showAccessoryTableAlert:fileArray nameKey:@"attname" pathKey:@"attpath"];
        
    }
}

#pragma mark
#pragma mark BackResultDataDelagate

- (void) backResultDataKey:(id)key dataValue:(id)backValue
{
    [self.resultData removeAllObjects];
    [self.tableView refreshData];
    [self.tableView headerBeginRefreshing];
}

@end
